import React, { useEffect, useState } from "react";
import './login.css';
import '../Loan/Apply/apply.css'
// import NavigateBar from "@/components/NavigateBar";
import Input from "@/components/Input";
// import OtpInput from "@/components/OtpInput";
import { useFormik } from "formik";
import classnames from "classnames";
import { useDispatch, useSelector } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { LOGIN_REQ_FAIL, LOGIN_REQ_SUCCESS, cleanLoginState, doLogin } from "@/store/actions/login";
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import icon_app_logo from "@/assets/icon_app_logo.png"
import icon_login_user from '@/assets/icon_login_user.png'
import icon_login_lock from '@/assets/icon_login_lock.png'
import icon_login_invite from '@/assets/icon_login_invite.png'
// import icon_login_code from '@/assets/icon_login_code.png'
// import icon_login_refuse from "@/assets/icon_login_refuse.png"
import "../../App.css";
import { SEND_OTP_REQ_FAIL, SEND_OTP_REQ_SUCCESS, cleanOtpState, sendOtp } from "@/store/actions/sendOtp";
import { cleanUserState } from "@/store/actions/userState";
// import { PageTag } from "@/utils/pageTag";
import { removeUserInfo } from "@/utils/storage";
import { saveEvent } from "@/store/actions/saveEvent";
// import { useLocation } from "react-router-dom/cjs/react-router-dom.min";
// import AddFavorite from "@/components/AddFavorite";
// import AddToHomeGifDialog from "@/components/AddToHomeGifDialog/AddToHomeGifDialog";
// import AddHomeEvent from "@/utils/addHomeEvent";
import AppParams from "@/utils/appParams";
import { LangThai } from "@/utils/langThai";
import { LangEn } from "@/utils/langEn";
// import { isEmptyString } from "@/utils/utils";
import axios from 'axios';
import { isCountryNrly, isCountryThai } from "@/utils/utils";
import { LangVnd } from "@/utils/langVnd";

/**
 * 登录页
 */
export default function Login() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //邀请码状态
    const [referrerCode, setReferrerCode] = useState("")

    //时区状态
    const [tzCode, setTzCode] = useState("")

    //ip状态
    const [ipInfo, setIpInfo] = useState({})

    //显示add home弹框
    // const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    // const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(false);

    //倒计时状态
    const [canStart, setCanStart] = useState(false);

    //需要转登录状态
    // const [needToLoginPage, setNeedToLoginPage] = useState(false);

    //需要转注册状态
    // const [needToRegisterPage, setNeedToRegisterPage] = useState(false);

    //获取Redux Store中的信息
    const sendOtpInfo = useSelector(state => state.sendOtp)

    //获取Redux Store中的信息
    const loginInfo = useSelector(state => state.login)

    // 文案翻译
    const [curLang, setCurLang] = useState(LangVnd);

    //router
    const history = useHistory()

    // const location = useLocation()

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //清空登录信息
    useEffect(() => {
        console.log("LOGIN-移除登录信息")
        //移除登录信息
        removeUserInfo()

        //清除登录信息
        dispatch(cleanLoginState())
        dispatch(cleanUserState())
        dispatch(cleanOtpState())

        //来源
        const dreferrer = document.referrer || ""
        console.log("document.referrer:==========" + dreferrer)

        //来源参数
        // const queryParams = new URLSearchParams(location.search);
        // const isRegister = queryParams.get('isRegister') || ""
        // if (isRegister === "YES") {
        //     setIsRegitsterType(true)
        // } else {
        //     setIsRegitsterType(false)
        // }

        //获取时区
        let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
        setTzCode(timeZone)
        console.log("timeZone:" + timeZone);
        if (isCountryNrly()) {
            setCurLang(LangEn)

        } else if (isCountryThai()) {
            setCurLang(LangThai)

        } else {
            setCurLang(LangVnd)
        }

        //邀请码
        const initInviteCode = AppParams.referrer
        setReferrerCode(initInviteCode)

        // 获取ip
        fetchIpAddress()

        //打点
        doHitEvent("LOGIN_START")

        return () => {
            //打点
            doHitEvent("LOGIN_END")
        }
    }, [])

    //监听验证码接口返回
    useEffect(() => {
        console.log("Login-监听验证码返回")
        console.log(sendOtpInfo)
        //获取短信发送成功返回
        if (sendOtpInfo.status === SEND_OTP_REQ_SUCCESS) {
            console.log("Login-短信发送成功")
            console.log(sendOtpInfo)
            //关闭loading
            setMaskVisible(false)

            //开始倒计时
            setCanStart(true)

        } else if (sendOtpInfo.status === SEND_OTP_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)

            //判断弹框
            // const otpResCode = sendOtpInfo.resCode || -1
            // if (otpResCode === 2001) {
            //     //需要弹提示--你是新客，需要注册
            //     setNeedToRegisterPage(true)
            //     setNeedToLoginPage(false)

            // } else if (otpResCode === 2002) {
            //     //需要弹提示--你是旧客，需要登录
            //     setNeedToRegisterPage(false)
            //     setNeedToLoginPage(true)
            // }
        }
    }, [sendOtpInfo])

    //监听登录接口返回
    useEffect(() => {
        //获取短信发送成功返回
        if (loginInfo.status === LOGIN_REQ_SUCCESS) {
            console.log("Login-登录成功")
            console.log(loginInfo)
            //关闭loading
            setMaskVisible(false)

            //清除登录信息
            dispatch(cleanLoginState())

            //跳转安装页
            history.replace('/installapp')

        } else if (loginInfo.status === LOGIN_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [loginInfo])


    // 获取ip
    const fetchIpAddress = async () => {
        try {
            // const response = await axios.get('https://api64.ipify.org?format=json');
            const response = await axios.get('https://ipinfo.io?token=4ef6f29947515a');
            const cip = response.data.ip;
            console.log("=====>ip: " + cip)
            console.log(response.data)
            setIpInfo(response.data || {})
        } catch (error) {
            console.error('Error fetching IP address:', error);
        }
    };

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            mobile: '',
            code: '',
            password: '',
            inviteCode: ''
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onLoginSubmit()
        },

        //校验
        validate(values) {
            const errors = {}
            // 非空
            if (!values.mobile || values.mobile === '') {
                if (isCountryThai()) {
                    errors.mobile = LangThai.loginPhoneMustNotEmpty

                } else if (isCountryNrly()) {
                    errors.mobile = LangEn.loginPhoneMustNotEmpty

                } else {
                    errors.mobile = LangVnd.loginPhoneMustNotEmpty
                }
            }

            // 包含中文
            if (values.mobile) {
                const chinesePattern = /[\u4e00-\u9fa5]/;
                const containsChinese = chinesePattern.test(values.mobile);
                if (containsChinese) {
                    if (isCountryThai()) {
                        errors.mobile = LangThai.loginIllegalInfo

                    } else if (isCountryNrly()) {
                        errors.mobile = LangEn.loginIllegalInfo

                    } else {
                        errors.mobile = LangVnd.loginIllegalInfo
                    }
                }
            }


            // if (!values.code || values.code === '') {
            //     errors.code = "verification code can't be none"
            // }
            if (!values.password || values.password === '' || (values.password.length < 8)) {
                if (isCountryThai()) {
                    errors.password = LangThai.loginPasswordMustNotEmpty

                } else if (isCountryNrly()) {
                    errors.password = LangEn.loginPasswordMustNotEmpty

                } else {
                    errors.password = LangVnd.loginPasswordMustNotEmpty
                }
            }

            return errors
        }
    })

    //请求短信接口
    const doSendOtp = async (mobile) => {
        console.log("doSendOtp: " + mobile);
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = sendOtp(mobile, referrerCode || "")

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求登录接口
    const doOtpLogin = async (mobile, password, ipInfo) => {
        console.log("doLogin: " + mobile + " , " + password);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = doLogin(mobile, password, referrerCode || "", ipInfo || {}, tzCode || "")

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //点击获取otp
    const onSendSmsCode = async () => {
        //验证是否在倒计时中
        //打点
        doHitEvent("LOGIN_OTP_CLICK")

        //验证手机号
        let mobile = form.values.mobile
        if (mobile.length < 4) {
            form.setTouched({ mobile: true })
            return
        }

        //请求发送短信
        doSendOtp(mobile)
    }

    //点击登录
    const onLoginSubmit = async () => {
        try {
            //打点
            doHitEvent("LOGIN_COMMIT_CLICK")

            //验证手机号
            let mobile = form.values.mobile

            //验证验证码
            //let code = form.values.code

            //验证密码
            let password = form.values.password

            const chinesePattern = /[\u4e00-\u9fa5]/;
            const containsChinese = chinesePattern.test(mobile);
            if (containsChinese) {
                if (isCountryThai()) {
                    Toast.show(LangThai.loginDataIllegal)

                } else if (isCountryNrly()) {
                    Toast.show(LangEn.loginDataIllegal)

                } else {
                    Toast.show(LangVnd.loginDataIllegal)
                }
                return
            }

            //请求登录
            doOtpLogin(mobile, password, ipInfo)

        } catch (e) {
            console.log(e)
        }
    }

    // 转登录弹框--点击确定
    // const onHandleToLoginPageMaskConfirm = () => {
    //     setNeedToRegisterPage(false)
    //     setNeedToLoginPage(false)
    //     history.goBack()
    // }

    // 转注册弹框--点击确定
    // const onHandleToRegisterPageMaskConfirm = () => {
    //     setNeedToRegisterPage(false)
    //     setNeedToLoginPage(false)
    //     history.goBack()
    // }

    // 点击add home监听
    // const onHandleAddToHome = (type) => {
    //     console.log(`点击add home监听: ${type}`)
    //     if (type === 'home') {
    //         AddHomeEvent.onHandleAddHomeEventClick()
    //     } else {
    //         AddHomeEvent.onHandleAddFavoriteEventClick()
    //     }
    // }

    // 关闭add home
    // const onHandleAddToHomeClose = () => {
    //     console.log(`点击close add home监听`)
    //     setAddHomeMaskVisible(false)
    // }

    return (
        <div className="login">
            {/* <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}></NavigateBar> */}

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumn contentHorizontalPadding loginTopEdge20Px">
                {/* logo与名称 */}
                <div className='loginApp'>
                    <div className='loginAppLogoContent'>
                        <img className="loginAppLogo" src={icon_app_logo} alt='' />
                        <span className='loginAppName'>{curLang.appName}</span>
                    </div>
                    <span className='loginAppUser'>{curLang.appShortTips}</span>
                </div>

                <form className="pageContentColumn loginTopEdge" onSubmit={form.handleSubmit}>

                    <span className='loginAppTips'>{curLang.appRegisterTips}</span>

                    {/* 手机号码输入框 */}
                    <div className="verifyInput">
                        <Input
                            id="mobile"
                            title={curLang.appUserName}
                            icon={icon_login_user}
                            name="mobile"
                            placeholder={curLang.loginEnter}
                            type="text"
                            value={form.values.mobile}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.mobile && form.touched.mobile && (
                        <div className="validate">{form.errors.mobile}</div>
                    )}

                    {/* 验证码输入框 */}
                    {/* <div className="verifyInput">
                        <OtpInput
                            id="code"
                            title="Enter the verification code"
                            name="code"
                            icon={icon_login_code}
                            placeholder="Enter"
                            maxLength={6}
                            type="text"
                            value={form.values.code}
                            onChange={form.handleChange}
                            onBlur={form.handleBlur}
                            onClickCallback={onSendSmsCode}
                            canStart={canStart}
                            autoComplete="off" />
                    </div>
                    {form.errors.code && form.touched.code && (
                        <div className="validate">{form.errors.code}</div>
                    )} */}

                    {/* 密码输入框 */}
                    <div className="verifyInput">
                        <Input
                            id="password"
                            title={curLang.appPassword}
                            name="password"
                            icon={icon_login_lock}
                            placeholder={curLang.loginEnter}
                            type="text"
                            value={form.values.password}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.password && form.touched.password && (
                        <div className="validate">{form.errors.password}</div>
                    )}

                    <span className='loginAppPasswordTips'>{curLang.appAccountTips}</span>


                    {/* 邀请码输入框 */}
                    {(referrerCode.length > 0) && <div className="verifyInput">
                        <Input
                            id="inviteCodereadonly"
                            title={curLang.appCouponCode}
                            icon={icon_login_invite}
                            name="inviteCodereadonly"
                            value={referrerCode}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            placeholder={curLang.loginEnter}
                            type="text"
                            readOnly="readOnly"
                            autoComplete="off" />
                    </div>}
                    {(referrerCode.length <= 0) && <div className="verifyInput">
                        <Input
                            id="inviteCode"
                            title={curLang.appCouponCode}
                            icon={icon_login_invite}
                            name="inviteCode"
                            value={referrerCode}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            placeholder={curLang.loginEnter}
                            type="text"
                            autoComplete="off" />
                    </div>}
                </form>

                {/* 登录提交 */}
                <div className={classnames('loginSubmit', (form.isValid && form.dirty) ? '' : 'loginSubmitBan disabled')} onClick={form.handleSubmit} disabled={true}>{curLang.appRegisterBtnText}</div>

                {/* 底部 margin */}
                <div className="loginBottomEdge"></div>

                {/* 转登录页弹框 */}
                {/* <Mask visible={needToLoginPage} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="applyOverlayBg">
                        <div className="applyOverlayContent">
                            <div className="applyOverlayContentIconCenter" onClick={onHandleToLoginPageMaskConfirm}>
                                <img className="applyOverlayIconCenter" src={icon_login_refuse} alt="" />
                            </div>

                            <div className="applyOverlayContentRowTitle">It is detected that you have already registered an account.</div>
                            <div className="applyOverlayContentRowTitle">Please login to your account through the login portal.</div>

                            <div className="homeApplyBtnLarge loginTopEdge" onClick={onHandleToLoginPageMaskConfirm}>
                                <div className="mainButtonGradient">OK</div>
                            </div>
                        </div>
                    </div>
                </Mask> */}

                {/* 转注册页弹框 */}
                {/* <Mask visible={needToRegisterPage} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="applyOverlayBg">
                        <div className="applyOverlayContent">
                            <div className="applyOverlayContentIconCenter" onClick={onHandleToRegisterPageMaskConfirm}>
                                <img className="applyOverlayIconCenter" src={icon_login_refuse} alt="" />
                            </div>

                            <div className="applyOverlayContentRowTitle">No account has been registered with this identity information.</div>
                            <div className="applyOverlayContentRowTitle">Please change your identity to log in or register a new account.</div>

                            <div className="homeApplyBtnLarge loginTopEdge" onClick={onHandleToRegisterPageMaskConfirm}>
                                <div className="mainButtonGradient">OK</div>
                            </div>
                        </div>
                    </div>
                </Mask> */}

                {/* add home gif dialog */}
                {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

                {/* load mask */}
                <Mask visible={maskVisible} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="loginOverlayContent">
                        <span style={{ fontSize: 24, color: '#3498DB' }} >
                            <DotLoading color="currentColor" />
                        </span>
                    </div>
                </Mask>
            </div>
        </div >
    )
}